﻿import VTitle from '@/components/common/MainTitle.vue'
export default {
  data () {
    return {
      titleName: '词典表维护',
      filterText: '',
      filterDic: [],
      isEdit: false,
      // 新增弹窗的部分
      dialogTitle: '',
      dialogFormVisible: false,
      submitType: '',
      ruleForm: {
        basicName: 'COMMON_',
        name: '',
        desc: '',
        istree: '否'
      },
      rules: {
        name: [
          {required: true, message: '词典表名称不能为空', trigger: 'blur'},
          {pattern: /^[a-zA-Z0-9_]+$/, message: '字段名称只能由英文、数字组成', trigger: 'blur'}
        ]
      },
      labelWidth: '110px',
      // 所有的词典表
      totalDic: [],
      // 当前词典表
      currentTable: '',
      // 右侧的检索
      searchKey: '',
      table: {
        tableData: [],
        tableColumn: []
      },
      operationType: '',
      multipleSelection: [],
      // 页码相关的数据
      totalLength: 0,
      currentPage: 1,
      pageSize: 10,
      isSearch: false,
      filterData: [],
      totalData: []
    }
  },
  created () {
    this.getAllDic()
  },
  methods: {
    // 获取所有的词典信息的列表
    getAllDic () {
      this.$get('/dictionarytable').then(data => {
        if (data.data.result.length) {
          // 默认选中第一个表
          if (!this.currentTable || this.submitType === 'add') {
            this.currentTable = data.data.result[0]
          } else {
            data.data.result.forEach(val => {
              if (val.dic_uid === this.currentTable.dic_uid) {
                this.currentTable = val
              }
            })
          }
          this.totalDic = data.data.result
          this.filterDic = data.data.result
          this.multipleSelection = []
          // 右侧展示词典表的内容
          if (this.currentTable.is_created) {
            this.getTableInfo(this.currentTable.dic_uid)
          }
        } else {
          this.totalDic = []
          this.filterDic = []
        }
      }).catch(error => {
        console.log(error)
      })
    },
    // 点击左侧的词典列表进行切换时
    changeTable (item) {
      this.currentTable = item
      this.operationType = ''
      if (item.is_created) {
        // 右侧展示词典表的内容
        this.getTableInfo(this.currentTable.dic_uid)
      } else {
        this.table.tableData = []
      }
    },
    // 获取指定的词典表的内容
    getTableInfo (uid) {
      this.operationType = ''
      this.searchKey = ''
      this.$get('/dictionaryset/' + uid).then(data => {
        if (data.data.result.code === 'failed') {
          this.$message({
            message: data.data.result.msg,
            type: 'warning'
          })
        } else if (data.data.result.code === 'success') {
          if (!data.data.result.istree) {
            this.table.tableColumn = [
              {
                indexName: 'code',
                text: '编号'
              },
              {
                indexName: 'value',
                text: '值'
              }
            ]
          } else {
            this.table.tableColumn = [
              {
                indexName: 'code',
                text: '编号'
              },
              {
                indexName: 'value',
                text: '值'
              },
              {
                indexName: 'level',
                text: '层级'
              },
              {
                indexName: 'p_code',
                text: '父节点编号'
              }
            ]
          }
          this.table.tableData = data.data.result.data
          this.totalData = data.data.result.data
          this.totalLength = data.data.result.data.length
          // 调用方法进行页面渲染
          this.showData(this.totalData)
        }
      }).catch(error => {
        console.log(error)
      })
    },
    // 新增词典表
    addTable () {
      this.dialogFormVisible = true
      this.dialogTitle = '新增词典表'
      this.submitType = 'add'
      this.ruleForm.name = ''
      this.ruleForm.desc = ''
      this.ruleForm.istree = '否'
    },
    // 提交新增
    submitAddTable () {
      let tableName = this.ruleForm.basicName + this.ruleForm.name
      let isTree = false
      if (this.ruleForm.istree === '是') {
        isTree = true
      }
      this.$post('/dictionarytable', {
        name: tableName,
        desc: this.ruleForm.desc,
        istree: isTree
      }).then(data => {
        if (data.data.result.code === 'failed') {
          this.$message({
            message: data.data.result.msg,
            type: 'warning'
          })
        } else if (data.data.result.code === 'success') {
          this.$message({
            message: '添加表成功！',
            type: 'success'
          })
          this.dialogFormVisible = false
          this.getAllDic()
        }
      }).catch(error => {
        console.log(error)
      })
    },
    // 编辑词典表
    handleEditTable (item) {
      this.dialogFormVisible = true
      this.dialogTitle = '编辑词典表'
      this.submitType = 'edit'
      this.currentTable = item
      this.ruleForm.name = item.dic_name.replace('COMMON_', '')
      this.ruleForm.desc = item.dic_desc
      if (item.is_tree) {
        this.ruleForm.istree = '是'
      } else {
        this.ruleForm.istree = '否'
      }
    },
    // 提交编辑
    submitEditTable () {
      let tableName = this.ruleForm.basicName + this.ruleForm.name
      let isTree = false
      if (this.ruleForm.istree === '是') {
        isTree = true
      }
      this.$patch('/dictionarytable/' + this.currentTable.dic_uid, {
        name: tableName,
        desc: this.ruleForm.desc,
        istree: isTree
      }).then(data => {
        if (data.data.result.code === 'failed') {
          this.$message({
            message: data.data.result.msg,
            type: 'warning'
          })
        } else if (data.data.result.code === 'success') {
          this.$message({
            message: '编辑词典表成功！',
            type: 'success'
          })
          this.dialogFormVisible = false
          this.getAllDic()
        }
      }).catch(error => {
        console.log(error)
      })
    },
    // 锁定一个词典表时
    handleLockTable (tableId) {
      this.$confirm('确定要锁定该表么?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        cancelButtonClass: 'el-button--info'
      }).then(() => {
        this.$patch('/dictionarytable/' + tableId + '/lock').then(data => {
          if (data.data.result.code === 'failed') {
            this.$message({
              message: data.data.result.msg,
              type: 'warning'
            })
          } else if (data.data.result.code === 'success') {
            this.$message({
              message: '该表已被锁定！',
              type: 'success'
            })
            this.getAllDic()
          }
        }).catch(error => {
          console.log(error)
        })
      }).catch(() => {})
    },
    // 解锁表时
    handleUnlockTable (tableId) {
      this.$confirm('确定要为该表解锁么?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        cancelButtonClass: 'el-button--info'
      }).then(() => {
        this.$patch('/dictionarytable/' + tableId + '/unlock').then(data => {
          if (data.data.result.code === 'failed') {
            this.$message({
              message: data.data.result.msg,
              type: 'warning'
            })
          } else if (data.data.result.code === 'success') {
            this.$message({
              message: '该表已成功解锁！',
              type: 'success'
            })
            this.getAllDic()
          }
        }).catch(error => {
          console.log(error)
        })
      }).catch(() => {})
    },
    // 点击弹窗的确定按钮
    submitForm (forms) {
      this.$refs[forms].validate((valid) => {
        if (valid) {
          if (this.submitType === 'add') {
            this.submitAddTable()
          } else if (this.submitType === 'edit') {
            this.submitEditTable()
          }
        } else {
          return false
        }
      })
    },
    // 点击弹窗的取消按钮
    resetForm (forms) {
      this.$refs[forms].resetFields()
      this.dialogFormVisible = false
    },
    closeDialog () {
      this.$refs.ruleForm.clearValidate()
    },
    // 删除词典表
    handleDeleteTable (tableId) {
      this.$confirm('此操作将永久删除该词典表, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        cancelButtonClass: 'el-button--info'
      }).then(() => {
        this.$delete('/dictionarytable/' + tableId).then((data) => {
          if (data.status === 204) {
            this.$message({
              message: '删除成功！',
              type: 'success'
            })
            this.getAllDic()
          }
        }).catch((error) => {
          if (error.response.status === 404) {
            this.$message.error('删除失败，请重试！')
          }
        })
      }).catch(() => {})
    },
    // created表时
    createTable () {
      if (this.currentTable) {
        if (this.currentTable.is_locked) {
          this.$message({
            message: '该表已被锁定，需要解锁后才能进行建表',
            type: 'warning'
          })
        } else {
          this.$confirm('此操作将以该表的信息为模型在数据库中创建表, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            cancelButtonClass: 'el-button--info'
          }).then(() => {
            this.$patch('/dictionarytable/' + this.currentTable.dic_uid + '/create').then(data => {
              if (data.data.result.code === 'failed') {
                this.$message({
                  message: data.data.result.msg,
                  type: 'warning'
                })
              } else if (data.data.result.code === 'success') {
                this.$message({
                  message: '该表已经成功创建！',
                  type: 'success'
                })
                this.getAllDic()
              }
            }).catch(error => {
              console.log(error)
            })
          }).catch(() => {})
        }
      }
    },
    // drop表时
    dropTable () {
      if (this.currentTable) {
        if (!this.currentTable.is_created) {
          this.$message({
            message: '该表还未创建，无法进行删除操作',
            type: 'warning'
          })
        } else if (this.currentTable.is_locked) {
          this.$message({
            message: '该表已被锁定，需要解锁后才能进行删除',
            type: 'warning'
          })
        } else {
          this.$confirm('此操作将删除该表的信息为模型在数据库中创建的表, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            cancelButtonClass: 'el-button--info'
          }).then(() => {
            this.$patch('/dictionarytable/' + this.currentTable.dic_uid + '/drop').then(data => {
              if (data.data.result.code === 'failed') {
                this.$message({
                  message: data.data.result.msg,
                  type: 'warning'
                })
              } else if (data.data.result.code === 'success') {
                this.$message({
                  message: '该表已经成功删除！',
                  type: 'success'
                })
                this.getAllDic()
              }
            }).catch(error => {
              console.log(error)
            })
          }).catch(() => {})
        }
      }
    },
    // 向词典表中添加数据
    addTableData () {
      this.operationType = 'add'
      if (this.currentTable.is_tree) {
        this.table.tableData.unshift({
          code: '',
          value: '',
          level: '',
          p_code: '',
          newData: 'newData'
        })
      } else {
        this.table.tableData.unshift({
          code: '',
          value: '',
          newData: 'newData'
        })
      }
    },
    // 提交新增词典表数据时
    submitAddTableData () {
      if (this.table.tableData.length) {
        let newArry = []
        this.table.tableData.forEach(val => {
          // 在表格中所有的数据中，找到新增的数据
          if (val.newData === 'newData') {
            // 将新增数据中的 newData 属性和值去掉并保存到新的数组中
            let objExam = {}
            for (let key in val) {
              if (key !== 'newData') {
                objExam[key] = val[key]
              }
            }
            newArry.push(objExam)
          }
        })
        // 当有新增的数据时
        if (newArry.length) {
          let hadNullCode = false
          newArry.forEach(val => {
            if (val.code === '') {
              hadNullCode = true
            }
          })
          if (hadNullCode) {
            this.$message({
              message: '词典表的中数据编号不能为空',
              type: 'warning'
            })
          } else {
            this.$post('/dictionaryset', {
              id: this.currentTable.dic_uid,
              data: newArry
            }).then(data => {
              if (data.data.result.code === 'success') {
                this.$message({
                  message: '添加数据成功！',
                  type: 'success'
                })
                this.getAllDic()
                this.operationType = ''
              } else if (data.data.result.code === 'failed') {
                this.$message({
                  message: data.data.result.msg,
                  type: 'warning'
                })
              }
            }).catch(error => {
              console.log(error)
            })
          }
        } else {
          this.$message({
            message: '该词典表中还没有新增的数据数据，不需要提交',
            type: 'warning'
          })
        }
      } else {
        this.$message({
          message: '该词典表中还没有新增的数据数据，不需要提交',
          type: 'warning'
        })
      }
    },
    // 编辑词典表中的数据
    editTableData () {
      if (this.table.tableData.length) {
        this.operationType = 'edit'
      } else {
        this.$message({
          message: '该词典表中还没有数据，无法进行编辑操作',
          type: 'warning'
        })
      }
    },
    // 提交编辑的方法
    submitEditTableData () {
      let hadNullCode = false
      this.table.tableData.forEach(val => {
        if (val.code === '') {
          hadNullCode = true
        }
      })
      if (hadNullCode) {
        this.$message({
          message: '词典表的中数据编号不能为空',
          type: 'warning'
        })
      } else {
        this.$patch('/dictionaryset/' + this.currentTable.dic_uid, {
          data: this.table.tableData
        }).then(data => {
          if (data.data.result.code === 'success') {
            this.$message({
              message: '编辑数据成功',
              type: 'success'
            })
            this.getAllDic()
            this.operationType = ''
          } else if (data.data.result.code === 'failed') {
            this.$message({
              message: data.data.result.msg,
              type: 'warning'
            })
          }
        }).catch(error => {
          console.log(error)
        })
      }
    },
    // 右侧的取消按钮时
    resetTableData () {
      this.operationType = ''
      this.getAllDic()
    },
    // 点击确定提交的按钮时
    submitTableData () {
      if (this.operationType === 'edit') {
        this.submitEditTableData()
      } else if (this.operationType === 'add') {
        this.submitAddTableData()
      }
    },
    // 删除词典表中的数据
    handleSingleDelete (row, index) {
      // 当为新增时移除新增项时
      if (this.operationType === 'add') {
        this.table.tableData.splice(index, 1)
      } else {
        this.submitDeleteTableData([row])
      }
    },
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    handlemultipleDelete () {
      if (this.multipleSelection.length) {
        this.submitDeleteTableData(this.multipleSelection)
      } else {
        this.$message({
          message: '没有选中应该删除的数据',
          type: 'warning'
        })
      }
    },
    submitDeleteTableData (fromDelete) {
      let deleteArray = []
      fromDelete.forEach(val => {
        deleteArray.push(val.code)
      })
      this.$confirm('此操作将永久删除数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        cancelButtonClass: 'el-button--info'
      }).then(() => {
        this.$delete('/dictionaryset/' + this.currentTable.dic_uid, {
          data: {
            code: deleteArray.join()
          }
        }).then(data => {
          if (data.status === 204) {
            this.$message({
              message: '数据删除成功',
              type: 'success'
            })
            this.getAllDic()
          }
        }).catch(error => {
          console.log(error)
        })
      }).catch(() => {})
    },
    // 将页码与数据关联
    showData (myData) {
      // 渲染表格的数据存放在 this.table.tableData 中
      this.table.tableData = []
      if (myData.length) {
        let from = (this.currentPage - 1) * this.pageSize
        let to = this.currentPage * this.pageSize
        if (to > myData.length) {
          to = myData.length
        }
        for (; from < to; from++) {
          this.table.tableData.push(myData[from])
        }
      }
    },
    // 底部页码的部分
    handleSizeChange (val) {
      this.pageSize = val
      // 需要判断是否是检索的数据
      if (this.isSearch) {
        this.showData(this.filterData)
      } else {
        this.showData(this.totalData)
      }
    },
    handleCurrentChange (val) {
      this.currentPage = val
      // 需要判断是否是检索的数据
      if (this.isSearch) {
        this.showData(this.filterData)
      } else {
        this.showData(this.totalData)
      }
    }
  },
  watch: {
    // 左侧的检索词典表名称
    filterText: {
      handler: function (val, oldVal) {
        // 当检索的内容为空时需要将表格的内容还原
        if (this.$trim(val) === '') {
          this.filterDic = this.totalDic
        } else {
          // 检索结果的数据存放在 this.filterDic 中
          this.filterDic = []
          // 所有的数据进行循环
          this.totalDic.forEach((value) => {
            // 进行检索匹配
            if (value.dic_name.toString().indexOf(this.filterText) !== -1 || value.dic_desc.toString().indexOf(this.filterText) !== -1) {
              this.filterDic.push(value)
            }
          })
        }
      },
      deep: true
    },
    // 右侧检索编号的功能
    searchKey: {
      handler: function (val, oldVal) {
        // 当检索的内容为空时需要将表格的内容还原
        if (this.$trim(val) === '') {
          this.pageSize = 10
          this.currentPage = 1
          this.totalLength = this.totalData.length
          this.isSearch = false
          // 调用方法进行页面渲染
          this.showData(this.totalData)
        } else {
          // 检索结果的数据存放在 this.filterData 中
          this.filterData = []
          // 所有的数据进行循环
          this.totalData.forEach((value) => {
            // 进行检索匹配
            if (value.code.toString().indexOf(this.searchKey) !== -1) {
              this.filterData.push(value)
            }
          })
          this.isSearch = true
          this.currentPage = 1
          this.totalLength = this.filterData.length
          // 调用方法进行页面渲染
          this.showData(this.filterData)
        }
      },
      deep: true
    }
  },
  components: {
    VTitle
  }
}